#!/usr/bin/python
# -*- coding=utf-8 -*-
# author : fzk
# date: 20220218
# version: 0.1

from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import END
from SearchXml import StrToXml
from SearchJson import DoJson
import json
import pyperclip

def SearchReport():
    GUI = tk.Tk()  # 创建窗口对象的背景色
    try:
            path = StringVar()
            file = StringVar()
            comvalue = StringVar()
            radio = IntVar()
            button1 = IntVar()
            child = []
            ed_child = []
            def choose():
                print(teet.get())
                # print(comvalue.get())
                # print(comvalue.get().split('(')[1][:-1])

            def Search_cus():
                tx = []
                dic_p = {}
                if child:
                    child[0].destroy()
                    child.clear()

                for i in text.get('0.0', 'end').split('\n'):
                    if i:
                        if radio.get():
                            tx.append(i.lower())
                        else:
                            tx.append(i)

                # 排序
                def tree1_sort_column(tv, col, reverse):  # tree1、列名、排列方式
                    l = [(tv.set(k, col), k) for k in tv.get_children('')]
                    # print(tv.get_children(''))
                    l.sort(reverse=reverse)  # 排序方式
                    # rearrange items in sorted positions
                    for index, (val, k) in enumerate(l):  # 根据排序后索引移动
                        tv.move(k, '', index)
                        # print(k)
                    tv.heading(col, command=lambda: tree1_sort_column(tv, col, not reverse))  # 重写标题，使之成为再点倒序的标题

                inp = txt.get('0.0', 'end')
                # 查询结果
                if button1.get()==1:
                    # js_d = json.loads(txt.get('0.0', 'end'))
                    if  inp.strip()[0] != '{':
                        messagebox.showinfo('提示信息', '报告输入格式错误，请确认报告格式')
                    else:
                        str_tit = DoJson().search_v(txt.get('0.0', 'end'), tx)

                else:
                    if  inp.strip()[0] != '<':
                        messagebox.showinfo('提示信息', '报告输入格式错误，请确认报告格式')
                    else:
                        str_tit = StrToXml(txt.get('0.0', 'end'), tx, teet.get())

                # print(str_tit[0])
                js_d = str_tit[3]
                Information = tk.LabelFrame(GUI, text="共找到" + str(len(str_tit[0])) + "条数据", padx=10,

                                            pady=10)  # 水平，垂直方向上的边距均为10
                Information.place(x=20, y=200, width=len(tx) * 120, height=350)
                child.append(Information)
                ybar1 = Scrollbar(Information, orient='vertical')  # 竖直滚动条
                xbar1 = Scrollbar(Information, orient=HORIZONTAL)  # 竖直滚动条
                tree1 = ttk.Treeview(Information, show='headings', columns=str_tit[2], yscrollcommand=ybar1.set,
                                     xscrollcommand=xbar1.set)

                def Copy_Do():
                    if button1.get()==1:
                        pyperclip.copy(json.dumps(js_d))
                    else:
                        pyperclip.copy(str(js_d))
                    messagebox.showinfo('提示信息', '复制成功，直接粘贴即可')
                for col in str_tit[2]:
                    tree1.heading(col, text=col, command=lambda _col=col: tree1_sort_column(tree1, _col, False))  # 行标题
                    tree1.column(col, width=108, anchor='center')  # 每一行的宽度,'w'意思为靠右.grid(pady=1, column=0, row=3, rowspan=2)
                tk.Button(Information, text="复制数据", width=14, height=1, command=Copy_Do).pack(side=TOP,expand=FALSE, fill=BOTH)
                tree1.pack(side=LEFT, fill=BOTH)
                ybar1.pack(side=RIGHT, fill=Y)
                xbar1.pack(side=BOTTOM, fill=X)
                ybar1['command'] = tree1.yview
                xbar1['command'] = tree1.xview
                tree1.bind('<ButtonRelease-1>', lambda event: tree1click1(event, tree1))
                # tree1.bind('<Double-1>', set_cell_value)  # 双击左键进入编辑

                for u in str_tit[0]:
                    tree1.insert("", "end", values=u)
                tup_i = tree1.get_children()
                for g, o in enumerate(str_tit[1]):
                    dic_p[tup_i[g]] = o
                # print(dic_p)

            # 点击列表数据方式
                def tree1click1(event, tree1):
                    if ed_child:
                        ed_child[0].destroy()
                        ed_child.clear()
                    Edit_v = tk.LabelFrame(GUI, text="修改数据", padx=10, pady=10)  # 水平，垂直方向上的边距均为10
                    Edit_v.place(x=20, y=580, width=len(tx) * 120, height=100)
                    ed_child.append(Edit_v)
                    # 修改数据
                    def Edit_Do():
                        # print(tree1.selection()[0])
                        for i, v in enumerate(edit_v1):
                            tree1.set(tree1.selection()[0], column=i, value=v.get())
                            if button1.get()==1:
                                DoJson().set_v(js_d, dic_p[tree1.selection()[0]][i], v.get())
                            else:
                                dic_p[tree1.selection()[0]][i].string = v.get()

                    # def Copy_Do():
                    #     pyperclip.copy(json.dumps(js_d))
                    #     messagebox.showinfo('提示信息', '复制成功，直接粘贴即可')
                            # print(i.get())

                    edit_v1 = []
                    item_text = tree1.item(tree1.selection()[0], "values")
                    for idn, col in enumerate(tx):
                        col = ttk.Entry(Edit_v, width=14)
                        edit_v1.append(col)
                        col.grid(pady=3, column=idn, row=1)
                        col.insert(INSERT, item_text[idn])
                        if idn == len(tx) - 1:
                            tk.Button(Edit_v, text="修改数据", width=14, height=1, command=Edit_Do).grid(pady=2,column=idn,row=2)
                        # tk.Button(Edit_v,text="复制数据", width=14, height=1,command=Copy_Do).grid(pady=2, column=idn-1, row=2)

            #发送指令

            Send = tk.LabelFrame(GUI, text="发送指令", padx=10, pady=10)  # 水平，垂直方向上的边距均为 10
            Send.place(x=20, y=20, width=360, height=180)
            ttk.Label(Send, text="查询格式:").grid(column=0, row=0, rowspan=2)
            comboxlist = ttk.Radiobutton(Send,text='Json',value=1,variable=button1,command=choose)
            comboxlist1 = ttk.Radiobutton(Send,text='Xml',value=2,variable=button1,command=choose)
            comboxlist.grid(column=1, row=0, pady=10, rowspan=2)
            comboxlist1.grid(column=2, row=0, pady=10, rowspan=2)
            button1.set(1)



            #自定义查询
            teet =StringVar()
            ttk.Label(Send, text="查询内容:").grid(column=0, row=2, rowspan=2)
            txt = Text(Send,  width=15, height=2, wrap='none')
            txt.grid(column=1, row=2, rowspan=2)
            tk.Button(Send, text="自定义查询", command=Search_cus).grid(pady=5, column=2, row=2, rowspan=2)
            # ttk.Label(Send, text="是否报告:").grid(column=0, row=4, rowspan=2)

            ttk.Label(Send, text="指定父节点:").grid(column=0, row=4, pady=10,rowspan=2)
            ent = ttk.Entry(Send,textvariable=teet,width=15)
            ent.grid(column=1, row=4,pady=10, rowspan=2)
            #查询字段
            Send1 = tk.LabelFrame(GUI, text="输入查询字段", padx=5, pady=5)  # 水平，垂直方向上的边距均为 10
            Send1.place(x=400, y=20, width=360, height=180)
            ck1 = tk.Checkbutton(Send1, text='转为小写', variable=radio)
            # ck1.grid(column=0, row=1, pady=1, rowspan=2)
            ck1.pack(side=TOP,expand=YES,fill=Y)
            s1 = Scrollbar(Send1)
            s1.pack(side=RIGHT,fill=Y)
            text = Text(Send1,width=45, height=8, wrap='none',yscrollcommand=s1.set)
            text.pack(side=LEFT,fill=BOTH)
            # text.grid(pady=1, column=0, row=3, rowspan=2)
            s1 = Scrollbar(Send1)
            s1.config(command=text.yview)
            # s1.pack(side=RIGHT,fill=Y)
            # te
            # s1.grid(row=3, column=3, sticky='ns')
            # text.pack(expand=YES, fill=BOTH)

            EntrySend = tk.StringVar()
            Userin = tk.StringVar()
            def S_Report():
                print('切换')

            mebubar = Menu(GUI)
            mebubar.add_command(label="报告查询",command=S_Report)
            mebubar.add_command(label="报文加密",command=S_Report)
            GUI.config(menu=mebubar)



    except Exception as e:
            text.insert(END, e)
    GUI.geometry("800x780")
    GUI.title('json/xml数据查看修改')
    GUI.mainloop()  # 进入消息循环
if __name__=='__main__':
    SearchReport()
    # GUI.geometry("800x780")
    # GUI.title('json/xml数据查看修改')
    # GUI.mainloop()  # 进入消息循环